package servlets;

import hibernatelogic.HibUsers;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import orm.Users;

@WebServlet("/add-user-servlet")
public class AddUserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Logger loggerAddUserServlet = Logger
			.getLogger(AddUserServlet.class);

	public AddUserServlet() {
		super();
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		HttpSession sess = request.getSession();
		
		/*
		 * Are you really an administrator?
		 */
		if (((String) sess.getAttribute("UserRole")).equals("3")) {
			
			HibUsers hibUser = new HibUsers();
			Users user = new Users();
			
			/*
			 * Requesting parameters
			 */
			String name = request.getParameter("nname");
			String login = request.getParameter("nlogin");
			String password = request.getParameter("npassword");
			int role = Integer.parseInt(request.getParameter("nrole"));
			
			/*
			 * Creating new user
			 */
			user.setName(name);
			user.setLogin(login);
			user.setPassword(password);
			user.setRole(role);
			
			try {
				/*
				 * Trying to add a new user
				 */
				hibUser.addUser(user);
			} catch (SQLException e) {
				loggerAddUserServlet.error(
						"Something wrong with AddUserServlet", e);
			} finally {
				/*
				 * Destroy & redirect
				 */
				hibUser = null;
				user = null;
				response.sendRedirect("/my-pet-project-0/AAddUser.jsp");
			}
		
			/*
			 * If you are not an administrator, then go away
			 */
		} else {
			response.sendError(response.SC_FORBIDDEN);
		}
	}
}
